#include "pm/manager.h"
#include <wx/intl.h>
#include <wx/msgdlg.h>

using namespace pm;

//{ Shotcuts
void pm::clear_all()
{
	ManagerST::Get()->clear_all();
}

bool pm::load(const wxString& dbname)
{
	return ManagerST::Get()->load(dbname);
}

const wxString& pm::get_db_name()
{
	return ManagerST::Get()->GetName();
}

bool pm::backup(const wxString& filename)
{
	return ManagerST::Get()->backup(filename);
}

bool pm::insert(db::Table& obj)
{
	return ManagerST::Get()->insert(obj);
}

bool pm::query(ICriteria& criteria)
{
	return ManagerST::Get()->query(criteria);
}

bool pm::select(ICriteria& criteria)
{
	return query(criteria);
}

bool pm::update(db::Table& obj)
{
	return ManagerST::Get()->update(obj);
}

//}


const wxString Manager::MEMORY = wxT(":memory:");

Manager::Manager()
{
}

Manager::~Manager()
{
}

bool Manager::is_db_open()
{
	return m_db.IsOpen();
}

void Manager::clear_all()
{
	m_db.ExecuteUpdate("delete from projects;");
	m_db.ExecuteUpdate("delete from work_requests;");
	m_db.ExecuteUpdate("delete from tags;");
	m_db.ExecuteUpdate("delete from tasks;");
	m_db.ExecuteUpdate("delete from tasks_history;");
	
	m_db.ExecuteUpdate("delete from sqlite_sequence where name='projects';");
	m_db.ExecuteUpdate("delete from sqlite_sequence where name='work_requests';");
	m_db.ExecuteUpdate("delete from sqlite_sequence where name='tags';");
	m_db.ExecuteUpdate("delete from sqlite_sequence where name='tasks';");
	m_db.ExecuteUpdate("delete from sqlite_sequence where name='tasks_history';");
}

bool Manager::load(const wxString& dbname)
{
	if (is_db_open()) {
		m_db.Close();
	}
	m_dbName.clear();
	
	try {
		m_db.Open(dbname);
	}
	catch (wxSQLite3Exception& e) {
		wxString msg = wxString::Format(_("Error loading file %s : %s"), dbname.c_str(), e.GetMessage().c_str());
		wxMessageBox(msg, _("Loading error"), wxOK|wxICON_ERROR);
		return false;
	}
	init_db();
	m_dbName = dbname;
	return true;
}

bool Manager::backup(const wxString& filename)
{
	try {
		m_db.Backup(filename);
	}
	catch (wxSQLite3Exception& e) {
		wxString msg = wxString::Format(_("Error while creating backup to file %s : %s"), filename.c_str(), e.GetMessage().c_str());
		wxMessageBox(msg, _("Backup error"), wxOK|wxICON_ERROR);
		return false;
	}
	return true;
}

bool Manager::insert(db::Table& obj)
{
	return is_db_open() && obj.insert(m_db);
}

bool Manager::query(ICriteria& criteria)
{
	return is_db_open() && criteria.query(m_db);
}

bool Manager::update(db::Table& obj)
{
	return is_db_open() && obj.update(m_db);
}
